<template>
	<view class="home_page">
		<u-navbar title="首页" :placeholder="true" leftIcon="" :titleStyle="{
			'color': '#000',
			'fontWeight': '700'
		}">
		</u-navbar>
		<u-transition :show="show" duration="1000" mode="true">
			<view class="henader_positioning"><!-- @click="clickPositioning" -->
				<view class="location">
					{{nickName}}&#12288({{houseRoomsize || 0 }}套房-{{ quantity}}间房源)
				</view>
				<!-- <view class="housenNmber">
					{{quantity || 0 }}套房源
				</view> -->
			</view>

			<view class="henader">
				<!-- 轮播图 -->
				<view class="header_banner">
					<!-- 	<u-swiper height="150" :list="bannerList" indicator indicatorMode="line" circular
						previousMargin="30" nextMargin="30"></u-swiper> -->

					<videoSwiper :circular="false" :list="bannerList" keyName="bannerUrl" height="150"
						@click="clickVideo" @playVideo="playVideo" previousMargin="30" nextMargin="30"></videoSwiper>
				</view>
				<!-- 功能项 -->
				<view class="functionality">
					<u-grid :border="false" col="4">
						<u-grid-item v-for="(item, index) of functionList" :key="item.id" @click="navgent(item)">
							<view class="icon">
								<image :src="item.icon" mode=""></image>
							</view>
							<text class="grid-text">{{item.name}}</text>
						</u-grid-item>
					</u-grid>
				</view>
				<!-- 待办事项 -->
				<view class="operate_box">
					<view class="header_box">
						<image src="../../static/operate/todolist_1.png"></image> <text class="title">待办事项</text>
					</view>
					<view class="operate_body">
						<u-grid :border="false" col="5">
							<u-grid-item v-for="(todoListItem,todoListIndex) in todoList" :key="todoListIndex"
								@click="clickitem(todoListItem)">
								<u-badge :type="type" max="99" :value="todoListItem.leaseConfirmCount" :offset="[-5,3]"
									:absolute="true" style="z-index: 999"></u-badge>
								<u-icon :name="todoListItem.name" :size="40"></u-icon>
								<text class="grid-text">{{todoListItem.title}}</text>
							</u-grid-item>
						</u-grid>
					</view>
				</view>
				<view class="operate_box">
					<view class="header_box">
						<image src="../../static/operate/browse.png"></image> <text class="title">经营概览</text>
					</view>
					<view class="operate_body">
						<u-grid :border="false">
							<u-grid-item class="operate_item" @click="rentStateClickitem(1)">
								<view class="name">
									已租
								</view>
								<view class="num">
									{{ formdata.leased?formdata.leased : '0' }} 间
								</view>
							</u-grid-item>
							<u-grid-item class="operate_item" @click="rentStateClickitem(0)">
								<view class="name">
									未租
								</view>
								<view class="num">
									{{ formdata.unknown ?formdata.unknown :'0' }} 间
								</view>
							</u-grid-item>
							<u-grid-item class="operate_item">
								<view class="name">
									本月签约数
								</view>
								<view class="num">
									{{ formdata.monthSign ? formdata.monthSign:'0' }} 条
								</view>
							</u-grid-item>
						</u-grid>

					</view>
					<view class="operate_body">
						<u-grid :border="false">
							<u-grid-item class="operate_item" @click="operateClickitem('./bill/bill?tag=currmoth')">
								<view class="name">
									本月应收
								</view>
								<view class="money">
									￥{{ formdata.receivable?formdata.receivable :'0' }}
								</view>
								<view class="num">
									{{ formdata.receivableNumber ? formdata.receivableNumber : '0' }} (笔)
								</view>
							</u-grid-item>
							<u-grid-item class="operate_item"
								@click="operateClickitem('./bill/bill?tag=currmothNoPay')">
								<view class="name">
									本月待收
								</view>
								<view class="money">
									￥{{ formdata.toCollect?formdata.toCollect :'0' }}
								</view>
								<view class="num">
									{{ formdata.toCollectNumber?formdata.toCollectNumber :'0' }} (笔)
								</view>
							</u-grid-item>
							<u-grid-item class="operate_item" @click="operateClickitem('./bill/bill?tag=overdue')">
								<view class="name">
									逾期未收
								</view>
								<view class="money">
									￥{{ formdata.overdue?formdata.overdue :'0' }}
								</view>
								<view class="num">
									{{ formdata.overdueNumber?formdata.overdueNumber :'0' }} (笔)
								</view>
							</u-grid-item>
						</u-grid>
					</view>
				</view>
			</view>
			<!-- <u-action-sheet :actions="list" cancelText="取消"  :closeOnClickOverlay="true" :closeOnClickAction="true" :show="showCall"  @select="selectClick"></u-action-sheet> -->
			<u-popup :show="showCall" @close="showCall = false">
				<view class="popup">
					<u-button :customStyle="{padding: '50rpx'}"
						@tap="callCustomerService(addHousePhone)">上架房源（微信同号）</u-button>
					<u-button :customStyle="{padding: '50rpx'}" icon="phone"
						@tap="callCustomerService(consultingPhone)">业务咨询电话</u-button>
					<u-button :customStyle="{padding: '50rpx'}" icon="info-circle"
						@tap="callCustomerService(complainPhone)">意见投诉电话</u-button>
					<u-gap height="10rpx" bgColor="#ececec"></u-gap>
					<u-button @click="showCall = false" :plain="true" :customStyle="{padding: '50rpx'}">取消</u-button>
				</view>
			</u-popup>
			<u-popup :show="showPopup" mode="center" :round="10" overlayOpacity="0.3"
				:customStyle="{backgroundColor: '#a6c6f7'}">
				<view class="popup_box" v-if="completeInfoState== '0'">
					<view class="title">
						欢迎您,新房东!
					</view>
					<view class="prompt">
						您需要完善资料信息，以便能</br>
						够更好的为您提供服务。
					</view>
					<view class="button_box">
						<u-button type="primary" class="sure" @click="determine">完善资料</u-button>
					</view>
				</view>
				<view class="popup_box" v-if="completeInfoState == '1'">
					<view class="title">
						欢迎您,新房东!
					</view>
					<view class="prompt">
						您的房东信息我们正在加速</br>审核中......
					</view>
				</view>
			</u-popup>
			<u-modal :show="showModal" :showCancelButton="true" @cancel="showModal = false" @confirm="confirm"
				cancelText="以后再说" confirmText="去维护">
				<view class="slot-content">
					您位于{{textToDisplay}}的总计{{total}}套空房已经三天没有出租或者刷新了，若这些空房已经出租，请您及时维护哦！
				</view>
			</u-modal>
		</u-transition>
		<u-toast ref="toast"></u-toast>

		<u-toast ref="uToast"></u-toast>
		<u-overlay opacity="1" duration="0" :show="VideoShowLook" @click="showTababr">
			<view class="" style="	display: flex;
		align-items: center;
		justify-content: center;
		height: 100%;">
				<video :src="videoSrc" style="width: 100%;" ref="video"  
					:autoplay="true"></video>
			</view>

		</u-overlay>
	</view>
</template>

<script>
	import {
		getCarousel,
		getBusiness,
		getQuantity,
		getRefresh,
		getRegeo,
		checkLandlordRefresh,
		badgeCount
	} from '@/api/home/index.js';
	import {
		getServerAppVersion
	} from '@/api/house/index.js';
	import {
		getUserInfo,
		getCustomer
	} from '../../api/my/index.js'
	import {
		baseURL
	} from "@/request/index.js"
	import videoSwiper from "../../components/swiper/index.vue"
	export default {
		data() {
			return {
				VideoShowLook: false,
				videoSrc: "",
				showModal: false,
				showCall: false,
				showPopup: false,
				showRefreshAlertPopup: false,
				completeInfoState: null,
				nickName: "",
				quantity: '0',
				houseRoomsize: '0', //房间数量，如果是整租的不管是几室的都算一间，合租的有几间对应的就是几个房源，几间房的意思
				textToDisplay: '',
				total: 0,
				todoList: [{
						name: '../../static/operate/confirm.png',
						title: '签约确认',
						url: './agency/agency',
						leaseConfirmCount: 1,
						id: 0
					},
					{
						name: '../../static/operate/sublet.png',
						title: '转租确认',
						url: './sublet/sublet',
						leaseConfirmCount: 1,
						id: 1
					},
					{
						name: '../../static/operate/orders.png',
						title: '待付列表',
						url: './orders/orders',
						leaseConfirmCount: 1,
						id: 2
					}, {
						name: '../../static/operate/late.png',
						title: '逾期账单',
						url: './bill/bill?tag=overdue',
						leaseConfirmCount: 1,
						id: 3
					}, {
						name: '../../static/operate/tobeCollected.png',
						title: '待收账单',
						url: './bill/bill?tag=currmothNoPayNoOver',
						id: 4
					}
				],
				list: [{
						name: '上架房源（微信同号）',
					},
					{
						name: '业务咨询电话',
					},
					{
						name: '意见投诉电话',
					}
				],
				show: true,
				bannerList: [],
				formdata: {},
				functionList: [{
						id: 0,
						name: "录入房源",
						icon: "../../static/operate/navigation.png",
						path: "./addhouse/option"
					},
					{
						id: 1,
						name: "添加租约",
						icon: "../../static/operate/contract_1.png",
						path: './addhouse/optioncommunity/optioncommunity'
					},
					{
						id: 2,
						name: "房态维护",
						icon: "../../static/operate/repair.png",
						path: './maintenance/index'
					},
					// {
					// 	id: 3,
					// 	name: "刷新房源",
					// 	icon: "../../static/operate/flushed.png",
					// 	flushed: true
					// },
					{
						id: 3,
						name: "联系客服",
						icon: "../../static/operate/service.png",
						cellClient: true
					}
				]
			}
		},
		onShow() {
			this.queryVersion()
			this.location = uni.getStorageSync('location') || "";
			this.nickName = uni.getStorageSync('userInfo') ? JSON.parse(uni.getStorageSync('userInfo')).nickName : "暂无"
			this.checkRefresh();
			this.getList();
		},

		onLoad() {
			this.userInfo();
			this.fetchQuantity()
			this.homeCarousel()
			this.business();
			this.getCallPhone();
			uni.setStorageSync('location', "请选择地区")
		},
		onPullDownRefresh() {

			uni.stopPullDownRefresh();
			this.fetchQuantity()
			this.homeCarousel()
			this.business();
			if (uni.getStorageSync('completeInfoState') != '2') {
				this.userInfo();

			}

			this.$refs.toast.show({
				message: "刷新成功",
				position: "bottom",
				type: 'success',
				duration: 1000
			})
		},

		// uni.setStorageSync('location', "请选择地区")
		// this.clickPositioning()

		components: {
			videoSwiper
		},

		methods: {
			showTababr() {
				var that = this
				uni.showTabBar({
					animation: true,
					success() {
						that.VideoShowLook = false;
					}
				})
			},
			//刷新房源
			async getFlushed() {
				const res = await getRefresh()
				if (res.data.code == 200) {
					this.$refs.uToast.show({
						message: '刷新成功',
						type: 'success'
					})
				} else {
					this.$refs.uToast.show({
						message: '刷新失败',
						type: 'error'
					})
				}
			},
			playVideo(url) {
				// console.log(url);
				this.videoSrc = url.bannerVideoUrl;
				this.VideoShowLook = true;
				uni.hideTabBar({
					animation: true,
				})

			},
			//用户信息
			async userInfo() {
				const res = await getUserInfo()
				if (res.data.code == 200) {
					this.completeInfoState = res.data.data.completeInfoState
					this.nickName = this.form = res.data.data.nickName
					uni.setStorageSync("completeInfoState", this.completeInfoState);
					uni.setStorageSync('userInfo', JSON.stringify(res.data.data))
					if (this.completeInfoState == '0' || this.completeInfoState == '1') {
						this.showPopup = true;
					} else {
						this.showPopup = false;
					}
				} else {
					this.$refs.uToast.show({
						message: res.data.msg,
						type: 'error'

					})
				}
			},
			//角标
			async getList() {
				const res = await badgeCount()
				if (res.data.code != 200) return this.$refs.uToast.show({
					message: res.data.msg,
					type: 'error'
				})
				this.todoList[0].leaseConfirmCount = res.data.data.leaseConfirmCount
				this.todoList[1].leaseConfirmCount = res.data.data.subletCount
				this.todoList[2].leaseConfirmCount = res.data.data.servicePayCount
				this.todoList[3].leaseConfirmCount = res.data.data.billOverdueCount
			},
			navgent(item) {
				if (item.cellClient) return this.showCall = true
				if (item.flushed) {
					this.getFlushed()
				} else {
					uni.navigateTo({
						url: item.path,
						animationType: this.animation.type,
						animationDuration: this.animation.time
					})
				}

			},
			selectClick(index) {
				// console.log(index)
			},
			//经纬度

			clickPositioning() {
				let loadding = uni.showLoading({
					title: '加载中',
					mask: true,
				})

				uni.getLocation({
					success: function(res) {
						uni.chooseLocation({
							longitude: res.longitude,
							latitude: res.latitude, //目标地经度
							// keyword: "", //搜索关键字
							success: (result) => {
								this.location = result.address
								uni.setStorageSync("location", this.location);
							},
							fail(err) {

								uni.hideLoading(loadding)
							}
						})
					},
					fail(err) {

					}
				});
			},
			//客服电话
			async getCallPhone() {
				//res.data.data.customerPhone
				const _this = this
				const res = await getCustomer()
				_this.addHousePhone = res.data.data[0].customerPhone
				_this.consultingPhone = res.data.data[1].customerPhone
				_this.complainPhone = res.data.data[2].customerPhone
			},
			//轮播图
			async homeCarousel() {
				const res = await getCarousel();
				if (res.data.code == 200) {
					this.bannerList = res.data.rows
					console.log(this.bannerList);
				} else {
					this.$refs.uToast.show({
						message: '获取轮播图失败',
						type: 'error'
					})
					return

				}
			},
			//获取经营概览
			async business() {
				const res = await getBusiness()
				if (res.data.code == 200) {
					this.formdata = res.data.data
					return
				}
			},
			//房东房源总数
			async fetchQuantity() {
				const res = await getQuantity()
				if (res.data.code == 200) {
					this.quantity = res.data.data.totalRooms
					this.houseRoomsize = res.data.data.houseRoomsize
					return
				}
				uni.startPullDownRefresh();

			},
			//刷新房源
			async getFlushed() {
				const res = await getRefresh()
				if (res.data.code == 200) {
					this.$refs.uToast.show({
						message: '刷新成功',
						type: 'success'
					})
				} else {
					this.$refs.uToast.show({
						message: '刷新失败',
						type: 'error'
					})
				}
			},
			// 完善资料
			determine() {
				uni.navigateTo({
					url: '../landlord/application',
					animationType: this.animation.type,
					animationDuration: this.animation.time
				})
			},
			//去维护
			confirm() {
				uni.navigateTo({
					url: '/pages/home/maintenance/index',
					animationType: this.animation.type,
					animationDuration: this.animation.time
				})
			},
			clickitem(todoListItem) {
				uni.navigateTo({
					url: todoListItem.url,
					animationType: this.animation.type,
					animationDuration: this.animation.time
				})
			},
			operateClickitem(url) {
				uni.navigateTo({
					url: url,
					animationType: this.animation.type,
					animationDuration: this.animation.time
				})
			},
			rentStateClickitem(state) {
				let url = '/pages/house/index'
				uni.setStorageSync('rentStateParams', JSON.stringify({
					rentState: state
				}));
				uni.switchTab({
					url: url,
					animationType: this.animation.type,
					animationDuration: this.animation.time
				})
			},
			//拨打客服电话
			async callCustomerService(phoneNumber) {
				uni.makePhoneCall({
					phoneNumber: phoneNumber,
				});


			},
			async checkRefresh() {
				const res = await checkLandlordRefresh();
				console.log(res, 12322);
				if (res.data.code == 200) {
					if (res.data.data.total > 0) {
						this.showRefreshAlertPopup = true;
						this.showModal = true
						this.textToDisplay = res.data.data.communityNamelist.join('、')
						this.total = res.data.data.total
					} else {
						this.showModal = false
					}
				}
			},
			RefreshAlertClose() {
				this.showRefreshAlertPopup = false
			},
			async queryVersion() {
				const res = await getServerAppVersion();
				const url = res.data.data.downUrl;
				var appServerAPIVersion = res.data.data.versionNo;
				//当前app版本号
				var currappVersion = plus.runtime.version;
				//var currappVersion='1.0.29';
				var v1 = appServerAPIVersion.split(".")[2];
				var v2 = currappVersion.split(".")[2];
				if (v1 > v2) {
					//蒙版提示更新不让操作
					uni.showModal({
						title: '更新提示',
						content: '发现新版本，需要更新才能继续使用！',
						showCancel: false,
						buttonText: '去下载',
						success: function(res) {
							plus.runtime.openURL(url)
						}
					});
				}
			}

		}
	}
</script>

<style lang="scss" scoped>
	@import "@/styles/global.scss";
	@import "@/styles/index.scss";

	.home_page {
		max-width: 100%;
		@include boxSing;
		min-height: 100vh;
		background-color: $pagebgc;
		overflow: hidden;

		.popup_box {
			padding: 40rpx;
			@include flexCenter;
			flex-direction: column;
			box-sizing: border-box;

			.title {
				font-size: 50rpx;
				font-weight: bold;
				line-height: 2;
			}

			.button_box {
				margin-top: 60rpx;
			}
		}

		.henader_positioning {
			width: 100%;
			position: fixed;
			@include flexBetween;
			box-sizing: border-box;
			font-size: 34rpx;
			font-weight: bold;
			padding: 20rpx;
			background-color: #fff;
			z-index: 99;

			.location {
				width: 70%;
				@include textOverflow;
				float: left;
			}

			.housenNmber {
				text-align: right;
				float: right;
				width: 28%;
				@include textOverflow;
			}
		}

		.henader {
			padding: 100rpx 20rpx;

			.header_banner {
				width: 100%;
				height: 150px;
				border-radius: 12px;
				@include boxshadow;
			}

			.functionality {
				width: 100%;
				margin: 20rpx 0;
				background-color: #fff;
				padding: 10rpx;
				box-sizing: border-box;
				border-radius: 20rpx;
				@include boxshadow;
				font-size: 30rpx;

				.icon {
					width: 80rpx;
					height: 80rpx;
					margin: 10rpx auto;

					image {
						width: 100%;
						height: 100%;
						filter: drop-shadow(rgb(204, 204, 209) 2px 2px 3px);
					}
				}
			}

			.operate_box {
				padding: 20rpx;
				background-color: #fff;
				border-radius: 20rpx;
				margin-bottom: 20rpx;
				@include boxshadow;

				.header_box {
					image {
						width: 70rpx;
						height: 70rpx;
						vertical-align: middle;
						border-radius: 40rpx;
					}

					.title {
						margin-left: 20rpx;
						font-size: 30rpx;
						font-weight: 700;
					}
				}

				.operate_body {
					margin-top: 30rpx;

					.grid-text {
						font-size: 14px;
						font-weight: bold;
						color: #666;
						padding: 10rpx 0;
						box-sizing: border-box;
					}

					.operate_item {
						width: 33%;
						text-align: center;
						padding: 20rpx;
						box-sizing: border-box;
						// background-color: #f2f2f2 !important;
						border-radius: 10rpx;
						// @include boxshadow;


						.name {
							font-size: 30rpx;
							font-weight: 700;
						}

						.money {
							font-size: 30rpx;
							margin: 10rpx 0;
							color: red;
							font-weight: bold;
						}

						.num {
							font-size: 30rpx;
							// margin-top: 10rpx;
						}
					}
				}
			}
		}
	}
</style>